<template>
  <el-dialog
      top="5vh"
      width="1200px"
      title="地图"
      :visible.sync="dialogValue"
      :close-on-click-modal="false"
      append-to-body
  >
    <SearchForm
        @search="onSearch"
        @reset="onReset"
        :search-list="searchList" :search-params="searchParams">
    </SearchForm>
    <!--    潜入腾讯地图选择定位 -->
    <div class="map-container">
      <div v-if="dialogValue" id="mapContainer" style="width: 100%; height: 500px;"></div>
      <div class="location-info" v-if="address.lat && address.lng">
        <p>当前位置：{{ address.formatted_address }}</p>
        <p>经度：{{ address.lng }}</p>
        <p>纬度：{{ address.lat }}</p>
        <p>省份：{{ address.province }}</p>
        <p>城市：{{ address.city }}</p>
        <p>区县：{{ address.district }}</p>
      </div>
    </div>
    <slot name="footer">
      <div
          :style="{
            textAlign: 'right',
            width: '100%',
            marginTop: '10px',
          }">
        <el-button @click="onClose">取消</el-button>
        <el-button type="primary" @click="onSave">保存</el-button>
      </div>
    </slot>
  </el-dialog>
</template>
<script>
import axios from "axios";
export default {
  name: "map",
  data() {
    return {
      dialogValue: false,
      map: null,
      marker: null,
      searchParams: {
        address: '',
        lat: '',
        lnt: ''
      },
      searchList: [
        {
          prop: 'address',
          label: '地址',
          name: 'input',
          type: 'textarea'
        },
      ],
      address: {
        lat: '',
        lng: '',
        formatted_address: '',
        province: '',
        city: '',
        district: '',
      }
    }
  },
  methods: {
    initMap() {
      this.getDefaultCenter().then(center => {
        //定义map变量，调用 TMap.Map() 构造函数创建地图
        this.map = new TMap.Map(document.getElementById('mapContainer'), {
          center: center,//设置地图中心点坐标
          zoom: 18,   //设置地图缩放级别
          pitch: 43.5,  //设置俯仰角
          rotation: 45    //设置地图旋转角度
        });

        // 添加地图点击事件
        this.map.on('click', (evt) => {
          const lat = evt.latLng.getLat();
          const lng = evt.latLng.getLng();
          this.updateMarker(lat, lng);
          this.reverseGeocode(lat, lng);
        });
        this.searchParams.lat = this.searchParams.lat || center.lat
        this.searchParams.lng = this.searchParams.lng || center.lng
        const _center = new TMap.LatLng(this.searchParams.lat, this.searchParams.lng)
        this.map.setCenter(_center)
        this.updateMarker(this.searchParams.lat, this.searchParams.lng)
        // 获取地址信息
        this.reverseGeocode(this.searchParams.lat, this.searchParams.lng)
      });
    },
    updateMarker(lat, lng) {
      if (this.marker) {
        this.marker.setMap(null)
      }
      this.marker = new TMap.MultiMarker({
        map: this.map,
        styles: {
          "marker": new TMap.MarkerStyle({
            width: 25,
            height: 35,
            anchor: { x: 12.5, y: 35 }
          })
        },
        geometries: [{
          id: 'marker',
          styleId: 'marker',
          position: new TMap.LatLng(lat, lng)
        }]
      });
    },
    open(location) {
      this.map = null
      this.searchParams = {
        ...location
      }
      console.log(this.searchParams)
      this.dialogValue = true
      // 确保地图在对话框显示后初始化
      this.$nextTick(() => {
        if (!this.map) {
          this.initMap()
        }
      })
    },
    onSearch() {
      let params = this.searchParams
      if (params.address) {
        // 使用腾讯位置服务WebServiceAPI进行地址解析
        const url = `/geocoder/v1/?address=${encodeURIComponent(params.address)}&key=${TMAP_KEY}`;
        axios.get(url).then(response => {
          const result = response.data;
          if (result.status === 0 && result.result.location) {
            const location = result.result.location;
            const address_components = result.result.address_components || result.result.address_component || {};
            // 更新地图中心点
            this.map.setCenter(new TMap.LatLng(location.lat, location.lng));
            // 更新标记
            if (this.marker) {
              this.marker.setMap(null);
            }
            this.marker = new TMap.MultiMarker({
              map: this.map,
              styles: {
                "marker": new TMap.MarkerStyle({
                  width: 25,
                  height: 35,
                  anchor: { x: 12.5, y: 35 }
                })
              },
              geometries: [{
                id: 'marker',
                styleId: 'marker',
                position: new TMap.LatLng(location.lat, location.lng)
              }]
            });
            // 更新地址信息
            this.address = {
              lat: location.lat,
              lng: location.lng,
              formatted_address: result.result.address || this.searchParams.address,
              province: address_components.province,
              city: address_components.city,
              district: address_components.district,
            };
          } else {
            this.$message.error('未找到该地址，请重试');
          }
        }).catch((e) => {
          this.$message.error('地址解析失败，请重试',e);
        });
      }
    },
    onReset() {
      this.searchParams.address = ''
      this.address = {
        lat: '',
        lng: '',
        formatted_address: '',
        province: '',
        city: '',
        district: '',
      }
      if (this.marker) {
        this.marker.setMap(null)
      }
    },
    onClose() {
      this.dialogValue = false
      this.onReset()
    },
    onSave() {
      if (!this.address.lat || !this.address.lng) {
        this.$message.warning('请先选择位置')
        return
      }
      this.$emit('save', this.address)
      this.onClose()
    },
    // 添加反向地理编码方法
    reverseGeocode(lat, lng) {
      const url = `/geocoder/v1/?location=${lat},${lng}&key=${TMAP_KEY}&get_poi=0`;
      axios.get(url).then(response => {
        const result = response.data;
        if (result.status === 0) {
          const address_components = result.result.address_components || result.result.address_component || {};
          this.address = {
            lat,
            lng,
            formatted_address: result.result.address || this.searchParams.address,
            province: address_components.province,
            city: address_components.city,
            district: address_components.district,
          };
        } else {
          this.$message.error('获取地址信息失败，请重试');
        }
      }).catch((e) => {
        this.$message.error('获取地址信息失败，请重试', e);
      });
    },
    // 根据省市区获取默认中心点
    async getDefaultCenter() {
      if (this.searchParams.address.trim()) {
        try {
          const address = this.searchParams.address.trim();

          if (!address) {
            return new TMap.LatLng(39.984120, 116.307484); // 默认北京
          }

          const response = await axios.get(`/geocoder/v1/`, {
            params: {
              address: address,
              key: TMAP_KEY // 请替换为实际的腾讯地图 Key
            }
          });
          if (response.data.status === 0) {
            const { lat, lng } = response.data.result.location;
            return new TMap.LatLng(lat, lng);
          }
        } catch (error) {
          console.error('获取地理编码失败:', error);
        }
      }
      return new TMap.LatLng(39.984120, 116.307484); // 默认北京
    },
  }
}
</script>

<style scoped lang="scss">
.map-container {
  position: relative;
  margin: 15px 0;
}

.location-info {
  margin-top: 10px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;

  p {
    margin: 5px 0;
    font-size: 14px;
  }
}
</style>
